$(document).ready(function() {
  $('div#menu ul li a').button();  
  $('div#toolbar ul li input').button();
  
  var paperX = $('div#content').offset().left;
  var paperY = $('div#content').offset().top;
  var paperW = $('div#content').innerWidth();
  var paperH = $('div#content').innerHeight();
  
  var paper = Raphael(paperX, paperY, paperW, paperH);
  
  paper.setStart();
  
  var firstC;
  
  var contentDOM = document.getElementById('content');
  
  window.DigitalBrain = {};
  
  window.DigitalBrain.drawMethod = 'line';
  window.DigitalBrain.drawColor = '#fff';
  window.DigitalBrain.itemCount = 0;
  window.DigitalBrain.fill = false;
  
  var lastX;
  var lastY;
  
  var lastMoveX;
  var lastMoveY;
  
  var middleOfOp;
  var lastDraw = null;
  
  var midX;
  var midY;
  
  $('input#circle').click(function() {
    window.DigitalBrain.drawMethod = 'circle';
  });
  
  $('input#line').click(function() {
    window.DigitalBrain.drawMethod = 'line';
  });
  $('input#point').click(function() {
    window.DigitalBrain.drawMethod = 'point';
  });
  $('input#rect').click(function() {
    window.DigitalBrain.drawMethod = 'rect';
  });
  $('input#text').click(function() {
    window.DigitalBrain.drawMethod = 'text';
  });
  
  $('input#clearcanvas').click(function() {
    var sf = paper.setFinish();
    for(var i = 0; i < sf.length; i++) {
      sf[i].animate({'opacity': 0,
                      'y': 400,
                      'cy': 400}, 500, function() {
          paper.clear();  
          paper.setStart();
      });
    }
  });
  
  $('li#whiteColor').click(function() {
    window.DigitalBrain.drawColor = 'white';
  });
  $('li#redColor').click(function() {
    window.DigitalBrain.drawColor = 'red';
  });
  $('li#blueColor').click(function() {
    window.DigitalBrain.drawColor = 'blue';
  });
  $('li#greenColor').click(function() {
    window.DigitalBrain.drawColor = 'green';
  });
  $('li#yellowColor').click(function() {
    window.DigitalBrain.drawColor = 'yellow';
  });
  $('li#purpleColor').click(function() {
    window.DigitalBrain.drawColor = 'purple';
  });
  $('li#aquaColor').click(function() {
    window.DigitalBrain.drawColor = 'aqua';
  });
  $('li#blackColor').click(function() {
    window.DigitalBrain.drawColor = 'black';
  });
  
  $('input#empty').click(function() {
    window.DigitalBrain.fill = false;
  });
  $('input#fill').click(function() {
    window.DigitalBrain.fill = true;
  });


  function initItems() {  
    $('div.item div.itemFrame button').on('click', function() {
      $(this).parents('.item').remove();
    });
  }
  
  $('div#content').on('mousedown', function(e) {
    middleOfOp = true;
    var eTarg = e.target;
    if(eTarg === contentDOM && eTarg.className !== 'itemFrame' & eTarg.className !== 'item') {
      if(e.which === 1) {
        lastX = parseInt(e.pageX - paperX);
        lastY = parseInt(e.pageY - paperY);
      }
    }
    
    firstC = paper.circle(lastX, lastY, 1);
    firstC.attr('stroke', window.DigitalBrain.drawColor);
  });
  
  $('div#content').on('mousemove', function(e) {
    
    if(lastDraw !== null) {
      lastDraw.remove();
    }
    
    lastMoveX = e.pageX - paperX;
    lastMoveY = e.pageY - paperY;
    
    
    var eTarg = e.target;
    if(middleOfOp) {
        if(window.DigitalBrain.drawMethod === 'line') {
          lastDraw = paper.path('M' + lastX + ' ' + lastY + 'L' + lastMoveX + ' ' + lastMoveY);
          lastDraw.attr('stroke', window.DigitalBrain.drawColor);
        }
        else if(window.DigitalBrain.drawMethod === 'circle') {
          var xLeg = lastMoveX - lastX;
          var yLeg = lastMoveY - lastY;
          var radius = Math.floor(Math.sqrt(Math.pow(xLeg, 2) + Math.pow(yLeg, 2)));
          lastDraw = paper.circle(lastX, lastY, radius);
          lastDraw.attr('stroke', window.DigitalBrain.drawColor);
          if(window.DigitalBrain.fill) {
            lastDraw.attr('fill', window.DigitalBrain.drawColor);
          }
        }
        else if(window.DigitalBrain.drawMethod === 'rect') {
          var rectTop;
          var rectLeft;
          var rectWidth;
          var rectHeight;
          
          if(lastX < lastMoveX) {
            rectLeft = lastX;
            rectWidth = lastMoveX - lastX;
          }
          else if(lastMoveX < lastX) {
            rectLeft = lastMoveX;
            rectWidth = lastX - lastMoveX;
          }
          
          if(lastY < lastMoveY) {
            rectTop = lastY;
            rectHeight = lastMoveY - lastY;
          }
          else if(lastMoveY < lastY) {
            rectTop = lastMoveY;
            rectHeight = lastY - lastMoveY;
          }
          lastDraw = paper.rect(rectLeft, rectTop, rectWidth, rectHeight);
          lastDraw.attr('stroke', window.DigitalBrain.drawColor);
          if(window.DigitalBrain.fill) {
            lastDraw.attr('fill', window.DigitalBrain.drawColor);
          }
        }
    }
  
  });
  
  $('div#content').on('touchstart', function(e) {
    var touch = e.targetTouches[0];
	var eTarg = touch.target;
    if(eTarg.className !== 'itemFrame' & eTarg.className !== 'item') {
      lastX = parseInt(touch.pageX - paperX);
      lastY = parseInt(touch.pageY - paperY);
    }
    
    firstC = paper.circle(lastX, lastY, 1);
    firstC.attr('stroke', window.DigitalBrain.drawColor);
  });
  
  
  $('div#content').on('mouseup', function(e) {
    middleOfOp = false;
    
    if(window.DigitalBrain.drawMethod !== 'point') {
      firstC.remove();
    }
    
    var eTarg = e.target;
    if(eTarg === contentDOM && eTarg.className !== 'itemFrame' & eTarg.className !== 'item') {
      if(e.which === 1) {
        var trueX = parseInt(e.pageX - paperX);
        var trueY = parseInt(e.pageY - paperY);

        if(window.DigitalBrain.drawMethod === 'line') {
          var p = paper.path('M' + lastX + ' ' + lastY + 'L' + trueX + ' ' + trueY);
          p.attr('stroke', window.DigitalBrain.drawColor);
        }
        else if(window.DigitalBrain.drawMethod === 'circle') {
          var xLeg = trueX - lastX;
          var yLeg = trueY - lastY;
          var radius = Math.floor(Math.sqrt(Math.pow(xLeg, 2) + Math.pow(yLeg, 2)));
          var p = paper.circle(lastX, lastY, radius);
          p.attr('stroke', window.DigitalBrain.drawColor);
          if(window.DigitalBrain.fill) {
            p.attr('fill', window.DigitalBrain.drawColor);
          }
        }
        else if(window.DigitalBrain.drawMethod === 'rect') {
          var rectTop;
          var rectLeft;
          var rectWidth;
          var rectHeight;
          
          if(lastX < trueX) {
            rectLeft = lastX;
            rectWidth = trueX - lastX;
          }
          else if(trueX < lastX) {
            rectLeft = trueX;
            rectWidth = lastX - trueX;
          }
          
          if(lastY < trueY) {
            rectTop = lastY;
            rectHeight = trueY - lastY;
          }
          else if(trueY < lastY) {
            rectTop = trueY;
            rectHeight = lastY - trueY;
          }
          var r = paper.rect(rectLeft, rectTop, rectWidth, rectHeight);
          r.attr('stroke', window.DigitalBrain.drawColor);
          if(window.DigitalBrain.fill) {
            r.attr('fill', window.DigitalBrain.drawColor);
          }
        }
        else if(window.DigitalBrain.drawMethod === 'text') {
          $('body').append('<div id="divDialog">Enter the text to add: <input type="text" class="drawText"></input><br>Text size in pixels (10 - 24)<input type="text" class="textSize"></input></div>');
          
          $('div#divDialog').dialog({
                                  'title': 'Add new text...',
                                  'buttons': [{
                                    'text': 'OK',
                                    'click': function() {
                                              var textText = $(this).children('input.drawText').val();
                                              var textSize = $(this).children('input.textSize').val();
                                              drawText(textText, textSize);
                                              $(this).dialog('destroy');
                                              $('div#divDialog').remove();
                                            }
                                    }]
                                  });
                                  
          
      
        }
        
        function drawText(text, textSize) {
          if(textSize > 24) {
            textSize = 24;
          }
          else if(textSize < 10) {
            textSize = 10;
          }
          
          var t = paper.text(lastX, lastY, text);
          t.attr('stroke', window.DigitalBrain.drawColor);
          t.attr('font-size', textSize);
        }
        
      }
    }
  });
  
  
  $('div#content').on('touchend', function(e) {
    
    if(window.DigitalBrain.drawMethod !== 'point') {
      firstC.remove();
    }
    var touch = e.targetTouches[0];
    var eTarg = touch.target;
    if(eTarg.className !== 'itemFrame' & eTarg.className !== 'item') {
        var trueX = parseInt(touch.pageX - paperX);
        var trueY = parseInt(touch.pageY - paperY);

        if(window.DigitalBrain.drawMethod === 'line') {
          var p = paper.path('M' + lastX + ' ' + lastY + 'L' + trueX + ' ' + trueY);
          p.attr('stroke', window.DigitalBrain.drawColor);
        }
        else if(window.DigitalBrain.drawMethod === 'circle') {
          var xLeg = trueX - lastX;
          var yLeg = trueY - lastY;
          var radius = Math.floor(Math.sqrt(Math.pow(xLeg, 2) + Math.pow(yLeg, 2)));
          var p = paper.circle(lastX, lastY, radius);
          p.attr('stroke', window.DigitalBrain.drawColor);
          if(window.DigitalBrain.fill) {
            p.attr('fill', window.DigitalBrain.drawColor);
          }
        }
        else if(window.DigitalBrain.drawMethod === 'rect') {
          var rectTop;
          var rectLeft;
          var rectWidth;
          var rectHeight;
          
          if(lastX < trueX) {
            rectLeft = lastX;
            rectWidth = trueX - lastX;
          }
          else if(trueX < lastX) {
            rectLeft = trueX;
            rectWidth = lastX - trueX;
          }
          
          if(lastY < trueY) {
            rectTop = lastY;
            rectHeight = trueY - lastY;
          }
          else if(trueY < lastY) {
            rectTop = trueY;
            rectHeight = lastY - trueY;
          }
          var r = paper.rect(rectLeft, rectTop, rectWidth, rectHeight);
          r.attr('stroke', window.DigitalBrain.drawColor);
          if(window.DigitalBrain.fill) {
            r.attr('fill', window.DigitalBrain.drawColor);
          }
        }
        else if(window.DigitalBrain.drawMethod === 'text') {
          $('body').append('<div id="divDialog">Enter the text to add: <input type="text" class="drawText"></input><br>Text size in pixels (10 - 24)<input type="text" class="textSize"></input></div>');
          
          $('div#divDialog').dialog({
                                  'title': 'Add new text...',
                                  'buttons': [{
                                    'text': 'OK',
                                    'click': function() {
                                              var textText = $(this).children('input.drawText').val();
                                              var textSize = $(this).children('input.textSize').val();
                                              drawText(textText, textSize);
                                              $(this).dialog('destroy');
                                              $('div#divDialog').remove();
                                            }
                                    }]
                                  });
                                  
          
      
        }
        
        function drawText(text, textSize) {
          if(textSize > 24) {
            textSize = 24;
          }
          else if(textSize < 10) {
            textSize = 10;
          }
          
          var t = paper.text(lastX, lastY, text);
          t.attr('stroke', window.DigitalBrain.drawColor);
          t.attr('font-size', textSize);
        }
        
      }
  });
  
  
  
  var itemCount = 0;
  
  $('a#about').click(function() {
    
    $('<div>'
    +'Digital Brain is a brainstorming tool providing drawing, note-taking and table creation tools, all for free.  Created by <a href="http://fonte.me">Jeremy Fonte</a> and released under the <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache License, version 2.0.</a>'
    +'</div>').dialog({
      title: 'About DigitalBrain',
      buttons: [ { text: "OK", click: function() {
          $(this).dialog("close");        } 
      }]
    });
  });
  
  $('a#new').click(function() {
    $('<div>'
    +'<input type="radio" name="newitem" value="note" checked=true>Note</input><br><input type="radio" name="newitem" value="table">Table</input>' +
    '</div>').dialog({
      title: 'Add New Item',
      buttons: [ { text: "OK", click: function() {
          $(this).dialog("close");
          var selection = $(this).children('input:checked').val();
          if(selection === 'note') {
            window.DigitalBrain.itemCount++;
            addNote();
          }
          else if(selection === 'table') {
            window.DigitalBrain.itemCount++;
            addTable();
          }
        } 
      }]
    });
    
    //adds a new item of type "note" - only supports multiline text, no rich text formatting.
    function addNote() {
    
    $('div#content').append('<div class="item note" id="item' + itemCount + '"><div class="itemFrame"><h4>Item ' + (itemCount + 1) + ' - Note</h4><button>X</button></div><div class="itemContent" contenteditable="true"</div></div>')
      addDragResize();
      initItems();
      itemCount++;
    }
    
    function addTable() {
      $('div#content').append('<div class="item table" id="item' + itemCount + '"><div class="itemFrame"><h4>Item ' + (itemCount + 1) + ' - Table</h4><button>X</button></div><div class="itemContent"></div></div>');
      
      var htmlStr = '';
      
      var columnLabels = ['', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O'];
      
      htmlStr += '<ul class="tableSet">';
      for(var y = 0; y < 4; y++) {
        if(y > 0) {
          htmlStr += '<li><ul class="tableRow">';
        }
        else {
          htmlStr += '<li><ul class="tableRow headerRow">';
        }
        for(var x = 0; x < 5; x++) {
          if(y === 0) {
            htmlStr += '<li class="labelCell" contenteditable="true">' + columnLabels[x] + '</li>';
          }
          else {
            if(x === 0) {  
              htmlStr += '<li class="labelCell">' + y + '</li>';
            }
            else {
              htmlStr += '<li contenteditable="true"></li>';
            }
          }
        }
        if(y === 0) {
          htmlStr += '<button id="newCol">+</button>'
        }
        htmlStr += '</ul></li>';
      }
      htmlStr += '<li><ul class="tableRow buttonRow"><button id="newRow">+</button></ul></li>';
      htmlStr += '</ul>';
      
      $('div#content div#item' + itemCount + ' div.itemContent').append(htmlStr)
      
      addDragResize();
      initItems();
      itemCount++;
    
        $('button#newCol').click(function() {
          
          var lastLetter = 0;
          $(' ul.headerRow li.labelCell').each(function() {
            lastLetter++;
          });
          
          //This seems like it should be plus one, but in fact the first label is empty so this works in providing the next letter
          var thisLetter = columnLabels[lastLetter];
          
          $(this).parents('ul.tableSet').find('ul.headerRow').append('<li class="labelCell" contenteditable="true">' + thisLetter + '</li>');
          $(this).parents('ul.tableSet').find('ul.tableRow').not('.buttonRow, .headerRow  ').append('<li contenteditable="true"></li>');
        });
        
        $('button#newRow').click(function() {
          var columns = 0
          $(this).parents('ul.tableSet').children('li').eq(2).children('ul.tableRow').children('li').each(function() {
            columns++;
          });
          
          $(this).parents('ul.tableSet').children('ul.tableRow').not('.buttonRow, headerRow').last().after('<ul class="tableRow"></ul>');
          for(var i = 0; i < columns; i++) {
            console.log(i);
            $(this).parents('ul.tableSet').children('ul.tableRow').not('.buttonRow, .headerRow').last().append('<li contenteditable="true"></li>');
          }
        });
    
    }
    

  function addDragResize() {
    $('div.item').draggable({
      handle: 'div.itemFrame', 
      drag: function(e) {
        var xMax = $('body').innerWidth();
        var yMax = $('body').innerHeight();
        var xDragMax = xMax - 10;
        var yDragMax = yMax - 10;
        
        if(e.pageX < 10 || e.pageY < 10 || e.pageX > xDragMax || e.pageY > yDragMax) {
          return false;
        }
        
      }
    }).resizable({
      stop: function(event, ui) {
        var thisWidth = $(this).innerWidth();
        var thisHeight = $(this).innerHeight();
        var frameHeight = $(this).children('div.itemFrame').innerHeight();
        $(this).children('div.itemContent').css({
          height: thisHeight - 16 - frameHeight,
          width: thisWidth - 16
        });
      } 
    });
  }
  });
  
});